
/*
 *  Copyright t lefering, David Given
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *  These are the four essential freedoms with GNU GPL software:
 *  1: freedom to run the program, for any purpose
 *  2: freedom to study how the program works, and change it to make it do what you wish
 *  3: freedom to redistribute copies to help your Free Software friends
 *  4: freedom to distribute copies of your modified versions to your Free Software friends
 *   ,           ,
 *  /             \
 * ((__-^^-,-^^-__))
 * `-_---'  `---_-'
 *  `--|o`   'o|--'
 *      \  `  /
 *       ): :(
 *       :o_o:
 *        "-"
 */

#include "globals.h"

/* We frequently mangle the names of symbols in order to achieve various
 * kinds of uniqueness, and so need to keep track of what we've mangled
 * them to.
 */

static int count = 0;

static avltree_t symbolstore = NULL;

static int compare_cb(const void *lhs, const void *rhs)
{
	const struct sinfo *n1 = lhs;
	const struct sinfo *n2 = rhs;
	unsigned int i1 = (unsigned int)(size_t)n1->sym;
	unsigned int i2 = (unsigned int)(size_t)n2->sym;
	if (i1 < i2) {
		return -1;
	} else if (i1 > i2) {
		return 1;
	} else {
		return 0;
	}
}

struct sinfo *lookup_sinfo_of_symbol(struct symbol *sym)
{
	struct sinfo key;
	const char *ident = NULL;
	struct sinfo *data = NULL;

	key.sym = sym;

	data = avl_search(symbolstore, compare_cb, &key, 0);

	if (data == NULL) {
		data = calloc(1, sizeof(struct sinfo));
		data->sym = sym;
		avl_insert(&symbolstore, compare_cb, data, NULL);

		if (sym->ident) {
			data->anonymous = 0;
			ident = show_ident(sym->ident);
		} else {
			data->anonymous = 1;
			data->here = 1;
			ident = "anon";
		}

		if (sym->ctype.modifiers & MOD_STATIC) {
			data->here = 1;
			data->name = aprintf("static_%d_%d_%s", unique, count, ident);
			count++;
		} else {
			/* rename main() into _main() for crt0 */
			if (strcmp(ident, "main") == 0) {
				data->name = aprintf("_%s", ident);
			} else {
				data->name = aprintf("%s", ident);
			}
		}
		if (verbose > 2) {
			printf("%s(): added \"%s\" for sym=%p\n", __func__, data->name, (void *)sym);
		}
	}

	return data;
}

char *show_symbol_mangled(struct symbol *sym)
{
	struct sinfo *node = lookup_sinfo_of_symbol(sym);
	return ((char *)node->name);
}

/* end */
